package com.hdy.web.exception;

import com.hdy.web.constant.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import com.hdy.web.pojo.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 自定义异常处理类
 * 针对不同的异常自定义不同的方法
 * 环绕通知
 * 切面:针对所有的controller中抛出的异常
 * 若使用@ControllerAdvice,则不会自动转换为JSON格式
 * @author Honetooyoung
 */
@Slf4j
@RestControllerAdvice
public class MyExceptionHandler {
    /**
     * 业务异常处理
     * @param e
     * @return ErrorInfo
     */
    @ExceptionHandler({CalculateException.class})
    public ResponseEntity<Object> calculateExceptionHandler(HttpServletRequest request, CalculateException e)
            throws CalculateException {
        log.error("订单计算异常：{}", e.getMessage());
        return ResponseEntity.of(e.getCode(), e.getMessage(), null);
    }

    /**
     * 只要抛出该类型异常,则由此方法处理
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Object> handleException(HttpServletRequest request, Exception e) throws Exception {
        log.error(e.getMessage(), e);
        return ResponseEntity.of(ResponseCode.SERVER_INTERNAL_ERROR, e.getMessage(), null);
    }
}
